/*
 *  (C) Copyright 2008 Insula T.I. Ltda.
 * 
 *  This file is part of Vulcano.
 *
 *  Vulcano is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Vulcano is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with Vulcano.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.openinsula.vulcano.orm.dao.hibernate;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.openinsula.vulcano.orm.dao.Dao;
import org.openinsula.vulcano.orm.dao.query.DaoQuery;
import org.openinsula.vulcano.orm.dao.query.DaoQueryVisitor;
import org.openinsula.vulcano.orm.dao.query.DistinctDaoQuery;
import org.openinsula.vulcano.orm.dao.query.ProjectionDaoQuery;
import org.openinsula.vulcano.orm.dao.query.SimpleDaoQuery;

/**
 * @author rebola
 * @author yanaga
 * @since 1.1
 * @see Dao
 * @see DaoQuery
 * @see HibernateDao
 */
public class LockDaoQueryVisitor implements DaoQueryVisitor<Void> {
	protected final Log logger = LogFactory.getLog(getClass());

	private final Query query;

	public LockDaoQueryVisitor(final Query query) {
		this.query = query;
	}

	public Void visit(final DistinctDaoQuery<?> distinctDaoQuery) {
		configureLock(distinctDaoQuery);
		return null;
	}

	public Void visit(final ProjectionDaoQuery<?> projectionDaoQuery) {
		return null;
	}

	public Void visit(final SimpleDaoQuery<?> simpleDaoQuery) {
		configureLock(simpleDaoQuery);
		return null;
	}

	private void configureLock(final DaoQuery<?> daoQuery) {
		LockMode lockMode = daoQuery.isLock() ? LockMode.UPGRADE : LockMode.NONE;
		query.setLockMode(HibernateDao.QUERY_ALIAS, lockMode);

		if (logger.isDebugEnabled()) {
			logger.debug("Applying LockMode " + lockMode + " on " + HibernateDao.QUERY_ALIAS);
		}
	}

}
